#include <sys/system.h>
#include <sys/string.h>
#include <gal/ptgui.h>
#include <sys/list.h>
#include <gal/surface.h>
#include <gal/font.h>
#include <gal/dc.h>

#ifdef PTGUI_FEATHER_USING_HZ_BMP

static void ptgui_hz_bitmap_font_draw_text(struct ptgui_font *font, struct ptgui_dc *dc, const char *text,
										   pt_ubase_t len, struct ptgui_rect *rect);
static void ptgui_hz_bitmap_font_get_metrics(struct ptgui_font *font, const char *text, ptgui_rect_t *rect);
struct ptgui_font_engine hz_bmp_font_engine =
{
	PT_NULL,
	PT_NULL,
	ptgui_hz_bitmap_font_draw_text,
	ptgui_hz_bitmap_font_get_metrics
};

static void ptgui_hz_bitmap_font_draw_text(struct ptgui_font *font, struct ptgui_dc *dc, const char *text,
										   pt_ubase_t len, struct ptgui_rect *rect)
{
	pt_base_t h;
	pt_uint8_t *str;
	struct ptgui_font_bitmap *bmp_font = (struct ptgui_font_bitmap *)(font->data);

	PT_ASSERT(bmp_font != PT_NULL);

	/* drawing height */
	h = (bmp_font->height + rect->y1 > rect->y2) ? rect->y2 - rect->y1 : bmp_font->height;

	str = (pt_uint8_t *)text;

	while (len > 0 && rect->x1 < rect->x2) {
		const pt_uint8_t *font_ptr;
		pt_ubase_t sect,
				   index;
		register pt_uint16_t i,
							 j,
							 k;

		/* calculate section and index */
		sect = *str - 0xA0;
		index = *(str + 1) - 0xA0;

		/* get font pixel data */
		font_ptr = bmp_font->bmp + (94 * (sect - 1) + (index - 1)) * (bmp_font->width + bmp_font->height);

		/* draw word */
		for (i = 0; i < h; i ++) {
			for (j = 0; j < 2; j++)
				for (k = 0; k < 8; k++) {
					if (((font_ptr[i * 2 + j] >> (7 - k)) & 0x01) != 0 && (rect->x1 + 8 * j + k < rect->x2)) {
						ptgui_dc_draw_point(dc, rect->x1 + 8 * j + k, rect->y1 + i);
					}
				}
		}

		/* move x to next character */
		rect->x1 += bmp_font->width;
		str += 2;
		len -= 2;
	}
}

static void ptgui_hz_bitmap_font_get_metrics(struct ptgui_font *font, const char *text, ptgui_rect_t *rect)
{
	struct ptgui_font_bitmap *bmp_font = (struct ptgui_font_bitmap *)(font->data);

	PT_ASSERT(bmp_font != PT_NULL);

	/* set metrics rect */
	rect->x1 = rect->y1 = 0;
	rect->x2 = (pt_int16_t)(bmp_font->width * pt_strlen((const char*)text));
	rect->y2 = bmp_font->height;
}

#endif
